//
//  YH_MyAccountViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/11/20.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_MyAccountViewController.h"
#import "AccountDetailViewController.h"

@interface YH_MyAccountViewController ()<UITableViewDataSource,UITableViewDelegate,ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UITableView *_tableView;
    
    __weak IBOutlet UIView *tipView;
    NSArray *list1;//表1 显示余额
    NSArray *list2;//表2 显示操作
    NSArray *list3;//表3 显示记录
    
    ASIFormDataRequest *getDataRequest;
    MBProgressHUD *postHud;
    NSDictionary *infoDic;//记录数据字典
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    ASIFormDataRequest *rollOutRequest;
    ASIFormDataRequest *changePwdRequest;
    //状态
    NSString *state;
}

@end

@implementation YH_MyAccountViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setdata];
    [self getdata];
    [self setUI];
    state = @"";
}
/**
 *  设置列表
 */
-(void)setdata{
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.backgroundView = nil;
    _tableView.backgroundColor = [UIColor clearColor];
    list1 = [NSArray arrayWithObjects:@"剩余天数:",@"账户余额:",@"卡内余额:",@"汇入合计:",@"汇出合计:",nil];
    list2 = [NSArray arrayWithObjects:@"转出",@"充值",@"密码重置",nil];
    list3 = [NSArray arrayWithObjects:@"汇入记录",@"支出记录", nil];
    
}
/**
 *  获取数据
 */
-(void)getdata{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在获取数据，请稍后...";
        }
        
        getDataRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        getDataRequest.requestMethod = @"POST";
        // 设置超时时间
        getDataRequest.timeOutSeconds = 60;
        getDataRequest.delegate = self;
        // 设置参数
        NSString *actionStr = @"huizong";
        paramsDict = @{@"uid":UNAME};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        getDataRequest.postBody = [paramsData mutableCopy];
        
        [getDataRequest startAsynchronous];
    }
}

#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            if (request == getDataRequest) {
                NSDictionary *info = result[@"info"];
                infoDic = [info mutableCopy];
                [_tableView reloadData];
            }else{
                [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
                [self getdata];
                [_tableView reloadData];
            }  
        } else {
            [SVProgressHUD showSuccessWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

/**
 *  设置UI
 */
-(void)setUI{
    self.navigationItem.title = @"账户管理";
    //返回
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    //tipView
    UIView *btn_back = [tipView viewWithTag:7];
    UIButton *btn_cancel = (UIButton *)[tipView viewWithTag:5];
    [btn_cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    UIButton *btn_commit = (UIButton *)[tipView viewWithTag:6];
    [btn_commit addTarget:self action:@selector(commit) forControlEvents:UIControlEventTouchUpInside];
    
    tipView.layer.cornerRadius = 5.0;
    btn_back.layer.cornerRadius = 5.0;
    btn_cancel.layer.cornerRadius = 5.0;
    btn_commit.layer.cornerRadius = 5.0;
    
    tipView.hidden = YES;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Custom Method
/**
 *  设置转出tip
 */
-(void)setRollOutUI{
    //tipView
    UILabel *title = (UILabel *)[tipView viewWithTag:1];
    title.text = @"账户转出";
    UILabel *labelRow1 = (UILabel *)[tipView viewWithTag:2];
    labelRow1.text = @"请输入会员名";
    labelRow1.textAlignment = NSTextAlignmentLeft;
    UILabel *labelRow2 = (UILabel *)[tipView viewWithTag:3];
    labelRow2.text = @"输入积分";
    UILabel *labelRow3 = (UILabel *)[tipView viewWithTag:4];
    labelRow3.hidden = YES;
    UITextField *textRow3 = (UITextField*)[tipView viewWithTag:44];
    textRow3.hidden = YES;
    textRow3.secureTextEntry = NO;
    UITextField *textRow1 = (UITextField*)[tipView viewWithTag:22];
    textRow1.secureTextEntry = NO;
    UITextField *textRow2 = (UITextField*)[tipView viewWithTag:33];
    textRow2.secureTextEntry = NO;
    UIButton *btn_commit = (UIButton *)[tipView viewWithTag:6];
    [btn_commit setTitle:@"转出" forState:UIControlStateNormal];

    tipView.hidden = NO;

}
/**
 *  设置重置密码tip
 */
-(void)setChangePassWord{
    //tipView
    UILabel *title = (UILabel *)[tipView viewWithTag:1];
    title.text = @"账户密码修改";
    UILabel *labelRow1 = (UILabel *)[tipView viewWithTag:2];
    labelRow1.text = @"原密码";
    labelRow1.textAlignment = NSTextAlignmentCenter;
    UILabel *labelRow2 = (UILabel *)[tipView viewWithTag:3];
    labelRow2.text = @"新密码";
    UILabel *labelRow3 = (UILabel *)[tipView viewWithTag:4];
    labelRow3.hidden = NO;
    labelRow3.text =@"确认密码";
    UITextField *textRow3 = (UITextField*)[tipView viewWithTag:44];
    textRow3.hidden = NO;
    textRow3.secureTextEntry = YES;
    UITextField *textRow1 = (UITextField*)[tipView viewWithTag:22];
    textRow1.secureTextEntry = YES;
    UITextField *textRow2 = (UITextField*)[tipView viewWithTag:33];
    textRow2.secureTextEntry = YES;
    UIButton *btn_commit = (UIButton *)[tipView viewWithTag:6];
    [btn_commit setTitle:@"确认" forState:UIControlStateNormal];
    
    tipView.hidden = NO;
}
-(void)tipViewReSet{
    UITextField *textRow1 = (UITextField *)[tipView viewWithTag:22];
    UITextField *textRow2 = (UITextField *)[tipView viewWithTag:33];
    UITextField *textRow3 = (UITextField *)[tipView viewWithTag:44];
    textRow1.text = @"";
    textRow2.text = @"";
    textRow3.text = @"";
}
/**
 *  取消
 */
-(void)cancel{
    [self tipViewReSet];
    tipView.hidden = YES;
}
/**
 *  提交
 */
-(void)commit{
    tipView.hidden = YES;
    if ([state isEqualToString:@"rollout"]) {
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            //BOOL b = postHud.hidden;
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在操作，请稍后...";
            }
            
            rollOutRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            rollOutRequest.requestMethod = @"POST";
            // 设置超时时间
            rollOutRequest.timeOutSeconds = 60;
            rollOutRequest.delegate = self;
            // 设置参数
            UITextField *textName = (UITextField *)[tipView viewWithTag:22];
            UITextField *textJifen = (UITextField *)[tipView viewWithTag:33];
            NSString *actionStr = @"jifenzhuanchuzong";
            paramsDict = @{@"uid":textName.text,@"cid":UID,@"jifen":textJifen.text};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            rollOutRequest.postBody = [paramsData mutableCopy];
            
            [rollOutRequest startAsynchronous];
        }
    }else{
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            //BOOL b = postHud.hidden;
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在操作，请稍后...";
            }
            
            changePwdRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            changePwdRequest.requestMethod = @"POST";
            // 设置超时时间
            changePwdRequest.timeOutSeconds = 60;
            changePwdRequest.delegate = self;
            // 设置参数
            UITextField *textOld = (UITextField *)[tipView viewWithTag:22];
            UITextField *textNew = (UITextField *)[tipView viewWithTag:33];
            UITextField *textNew1 = (UITextField *)[tipView viewWithTag:44];
            if (![textNew.text isEqualToString:textNew1.text]) {
                [SVProgressHUD showErrorWithStatus:@"两次密码不一致"];
                [self tipViewReSet];
                postHud.hidden = YES;
                return;
            }
            NSString *actionStr = @"mima";
            paramsDict = @{@"uid":UNAME,@"old":textOld.text,@"new":[textNew.text md5],@"news":[textNew1.text md5]};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            changePwdRequest.postBody = [paramsData mutableCopy];
            
            [changePwdRequest startAsynchronous];
        }
    }
    [self tipViewReSet];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UITableView Delegate 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId1 = @"cell1";
    static NSString *cellId2 = @"cell2";
    static NSString *cellId3 = @"cell3";
    switch (indexPath.section) {
        case 0:{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId1];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"AccountCell1" owner:nil options:nil][0];
                cell.backgroundColor = [UIColor whiteColor];
                cell.contentView.layer.cornerRadius = 5.0;
                cell.userInteractionEnabled = NO;
            }
            UILabel *title = (UILabel *)[cell.contentView viewWithTag:1];
            UILabel *name = (UILabel *)[cell.contentView viewWithTag:2];
            switch (indexPath.row) {
                case 0:{
                    NSString *str = infoDic[@"Cjifen"];
                    name.text = str.length == 0 ? @"0":str;
                }break;
                case 1:{
                    NSString *str = infoDic[@"YCJifen"];
                    name.text = [NSString stringWithFormat:@"%@元", ( str.length == 0 ? @"0" :str)];
                }break;
                case 2:{
                    NSString *str = infoDic[@"BKJifen"];
                    name.text = [NSString stringWithFormat:@"%@元", ( str.length == 0 ? @"0" :str)];
                }break;
                case 3:{
                    NSString *str = infoDic[@"huirujifen"];
                    name.text = [NSString stringWithFormat:@"%@元",( str.length == 0 ? @"0" :str)];
                }break;
                case 4:{
                    NSString *str = infoDic[@"huichujifen"];
                    name.text = [NSString stringWithFormat:@"%@元",(str.length == 0 ? @"0" :str)];
                }break;
                default:
                    break;
            }
            title.text = list1[indexPath.row];
            
            return cell;
        } break;
        case 1:{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId2];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"AccountCell2" owner:nil options:nil][0];
                cell.backgroundColor = [UIColor whiteColor];
                cell.contentView.layer.cornerRadius = 5.0;
            }
            UIImageView *title = (UIImageView *)[cell.contentView viewWithTag:1];
            UILabel *name = (UILabel *)[cell.contentView viewWithTag:2];
            title.image = [UIImage imageNamed:@"item_64"];
            name.text = list2[indexPath.row];
            
            return cell;
        } break;
        case 2:{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId3];
            if (!cell) {
                cell = [[NSBundle mainBundle]loadNibNamed:@"AccountCell2" owner:nil options:nil][0];
                cell.backgroundColor = [UIColor whiteColor];
                cell.contentView.layer.cornerRadius = 5.0;
            }
            UIImageView *title = (UIImageView *)[cell.contentView viewWithTag:1];
            UILabel *name = (UILabel *)[cell.contentView viewWithTag:2];
            title.image = [UIImage imageNamed:@"item_64"];
            name.text = list3[indexPath.row];
            
            return cell;
        } break;
        default:{
            return nil;
        } break;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 1:{
            switch (indexPath.row) {
                case 0:{//转出
                    state = @"rollout";
                    [self setRollOutUI];
                }break;
                case 1:{//充值
                    
                }break;
                case 2:{//密码重置
                    state = @"changepwd";
                    [self setChangePassWord];
                }break;
                default:
                    break;
            }
        }break;
        case 2:{
            switch (indexPath.row) {
                case 0:{//汇入记录
                    AccountDetailViewController *abouchement = [[AccountDetailViewController alloc]initWithNavTitle:@"汇入金额记录" type:@"1"];
                    [self.navigationController pushViewController:abouchement animated:YES];
                }break;
                case 1:{//支出记录
                    AccountDetailViewController *expend = [[AccountDetailViewController alloc]initWithNavTitle:@"支出金额记录" type:@"0"];
                    [self.navigationController pushViewController:expend animated:YES];
                }break;
                default:
                    break;
            }
            
        }break;
        default:
            break;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0 :{
            if (list1.count != 0) {
                return list1.count;
            }else{
                return 0;
            }
        }break;
        case 1 :{
            if (list2.count != 0) {
                return list2.count;
            }else{
                return 0;
            }
        }break;
        case 2 :{
            if (list3.count != 0) {
                return list3.count;
            }else{
                return 0;
            }
        }break;
        default:{
            return 0;
        } break;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
/**
 *  设置ios7 tableView 圆角
 *
 **/
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(tintColor)]) {
        if (tableView == _tableView) {    // self.tableview
            CGFloat cornerRadius = 5.f;
            cell.backgroundColor = UIColor.clearColor;
            CAShapeLayer *layer = [[CAShapeLayer alloc] init];
            CGMutablePathRef pathRef = CGPathCreateMutable();
            CGRect bounds = CGRectInset(cell.bounds, 5, 0);
            BOOL addLine = NO;
            if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
            } else if (indexPath.row == 0) {
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
                addLine = YES;
            } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
            } else {
                CGPathAddRect(pathRef, nil, bounds);
                addLine = YES;
            }
            layer.path = pathRef;
            CFRelease(pathRef);
            layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
            
            if (addLine == YES) {
                CALayer *lineLayer = [[CALayer alloc] init];
                CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
                lineLayer.frame = CGRectMake(CGRectGetMinX(bounds)+5, bounds.size.height-lineHeight, bounds.size.width-5, lineHeight);
                lineLayer.backgroundColor = tableView.separatorColor.CGColor;
                [layer addSublayer:lineLayer];
            }
            UIView *testView = [[UIView alloc] initWithFrame:bounds];
            [testView.layer insertSublayer:layer atIndex:0];
            testView.backgroundColor = UIColor.clearColor;
            cell.backgroundView = testView;
        }
    }
}

-(void)dealloc{
    [getDataRequest cancel];
    getDataRequest = nil;
}
@end
